package com.zdy.reflection;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by 逸足天涯
 * on 3/5/2020.
 */
//通过反射动态的创建对象
public class Test09 {
    public static void main(String[] args) throws
            ClassNotFoundException,NoSuchMethodException,NoSuchFieldException,
            InvocationTargetException, InstantiationException,IllegalAccessException{
        //获取Class 对象
        Class c1 = Class.forName("com.zdy.reflection.User");
        //构造一个对象
        User  user = (User) c1.newInstance();//本质上调用类的无参构造器
        System.out.println(user);

        //通过构造器创建对象
        Constructor constructor = c1.getDeclaredConstructor(int.class,String.class,int.class);
        User  user2 =(User) constructor.newInstance(12, "张三", 01);
        System.out.println(user2);


        //通过反射调用普通方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        //invoke 激活的意思(对象，属性值)
        setName.invoke(user,"王二小");
        System.out.println(user.getName());

        //通过反射操作属性
        Field name = c1.getDeclaredField("name");
        //关闭权限检测
        name.setAccessible(true);
        name.set(user,"熊大");
        System.out.println(user.getName());

    }


}